<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2048 游戏</title>
    <style>
        body {
            font-family: 'Arial Rounded MT Bold', 'Arial', sans-serif;
            background-color: #faf8ef;
            color: #776e65;
            text-align: center;
            margin: 0;
            padding: 20px;
        }
        
        .container {
            max-width: 500px;
            margin: 0 auto;
        }
        
        h1 {
            font-size: 60px;
            margin: 0;
            color: #776e65;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .score-container {
            background: #bbada0;
            padding: 10px 20px;
            border-radius: 5px;
            color: white;
            font-weight: bold;
            text-align: center;
        }
        
        .score-title {
            font-size: 16px;
        }
        
        .score-value {
            font-size: 24px;
        }
        
        .game-intro {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .restart-button {
            background: #8f7a66;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 20px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .restart-button:hover {
            background: #9f8b77;
        }
        
        .game-container {
            background: #bbada0;
            border-radius: 6px;
            padding: 15px;
            position: relative;
            margin-bottom: 20px;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-gap: 15px;
        }
        
        .cell {
            width: 100%;
            height: 0;
            padding-bottom: 100%;
            background: rgba(238, 228, 218, 0.35);
            border-radius: 3px;
            position: relative;
        }
        
        .tile {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 35px;
            font-weight: bold;
            border-radius: 3px;
            background: #eee4da;
            color: #776e65;
            transition: all 0.1s;
            z-index: 10;
        }
        
        .tile-2 { background: #eee4da; color: #776e65; }
        .tile-4 { background: #ede0c8; color: #776e65; }
        .tile-8 { background: #f2b179; color: white; }
        .tile-16 { background: #f59563; color: white; }
        .tile-32 { background: #f67c5f; color: white; }
        .tile-64 { background: #f65e3b; color: white; }
        .tile-128 { background: #edcf72; color: white; font-size: 30px; }
        .tile-256 { background: #edcc61; color: white; font-size: 30px; }
        .tile-512 { background: #edc850; color: white; font-size: 30px; }
        .tile-1024 { background: #edc53f; color: white; font-size: 25px; }
        .tile-2048 { background: #edc22e; color: white; font-size: 25px; }
        
        .game-over {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(238, 228, 218, 0.73);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            z-index: 100;
            display: none;
        }
        
        .game-over-text {
            font-size: 60px;
            font-weight: bold;
            color: #776e65;
            margin-bottom: 30px;
        }
        
        .instructions {
            margin-top: 20px;
            color: #776e65;
            line-height: 1.5;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>2048</h1>
            <div class="score-container">
                <div class="score-title">分数</div>
                <div class="score-value" id="score">0</div>
            </div>
        </div>
        
        <div class="game-intro">
            <p>合并相同数字的方块，直到获得2048！</p>
            <button class="restart-button" id="restart-button">新游戏</button>
        </div>
        
        <div class="game-container">
            <div class="grid" id="grid">
                <!-- 4x4网格将通过JavaScript动态生成 -->
            </div>
            
            <div class="game-over" id="game-over">
                <div class="game-over-text">游戏结束!</div>
                <button class="restart-button" id="try-again-button">再试一次</button>
            </div>
        </div>
        
        <div class="instructions">
            <p><strong>如何玩：</strong>使用键盘方向键(↑↓←→)或WASD移动方块。当两个相同数字的方块相撞时，它们会合并成一个!</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const gridDisplay = document.getElementById('grid');
            const scoreDisplay = document.getElementById('score');
            const restartButton = document.getElementById('restart-button');
            const tryAgainButton = document.getElementById('try-again-button');
            const gameOverDisplay = document.getElementById('game-over');
            
            let grid = [];
            let score = 0;
            const gridSize = 4;
            
            // 初始化游戏
            function initGame() {
                grid = Array(gridSize).fill().map(() => Array(gridSize).fill(0));
                score = 0;
                scoreDisplay.textContent = score;
                gameOverDisplay.style.display = 'none';
                
                // 清空网格显示
                gridDisplay.innerHTML = '';
                
                // 创建网格单元格
                for (let i = 0; i < gridSize; i++) {
                    for (let j = 0; j < gridSize; j++) {
                        const cell = document.createElement('div');
                        cell.classList.add('cell');
                        cell.dataset.row = i;
                        cell.dataset.col = j;
                        gridDisplay.appendChild(cell);
                    }
                }
                
                // 添加两个初始方块
                addRandomTile();
                addRandomTile();
                
                updateGridDisplay();
            }
            
            // 添加随机方块(2或4)
            function addRandomTile() {
                const emptyCells = [];
                
                // 找出所有空单元格
                for (let i = 0; i < gridSize; i++) {
                    for (let j = 0; j < gridSize; j++) {
                        if (grid[i][j] === 0) {
                            emptyCells.push({ row: i, col: j });
                        }
                    }
                }
                
                if (emptyCells.length > 0) {
                    // 随机选择一个空单元格
                    const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
                    // 90%概率生成2，10%概率生成4
                    grid[randomCell.row][randomCell.col] = Math.random() < 0.9 ? 2 : 4;
                    return true;
                }
                return false;
            }
            
            // 更新网格显示
            function updateGridDisplay() {
                const cells = document.querySelectorAll('.cell');
                
                cells.forEach(cell => {
                    const row = parseInt(cell.dataset.row);
                    const col = parseInt(cell.dataset.col);
                    const value = grid[row][col];
                    
                    // 清空单元格
                    cell.innerHTML = '';
                    
                    if (value !== 0) {
                        const tile = document.createElement('div');
                        tile.classList.add('tile', `tile-${value}`);
                        tile.textContent = value;
                        cell.appendChild(tile);
                    }
                });
            }
            
            // 移动方块
            function moveTiles(direction) {
                let moved = false;
                const oldGrid = JSON.parse(JSON.stringify(grid));
                
                // 根据方向处理移动
                switch (direction) {
                    case 'up':
                        for (let j = 0; j < gridSize; j++) {
                            let column = [];
                            for (let i = 0; i < gridSize; i++) {
                                if (grid[i][j] !== 0) {
                                    column.push(grid[i][j]);
                                }
                            }
                            
                            // 合并相同数字
                            for (let i = 0; i < column.length - 1; i++) {
                                if (column[i] === column[i + 1]) {
                                    column[i] *= 2;
                                    column[i + 1] = 0;
                                    score += column[i];
                                    scoreDisplay.textContent = score;
                                }
                            }
                            
                            // 移除0并填充
                            column = column.filter(val => val !== 0);
                            while (column.length < gridSize) {
                                column.push(0);
                            }
                            
                            // 更新列
                            for (let i = 0; i < gridSize; i++) {
                                if (grid[i][j] !== column[i]) {
                                    moved = true;
                                }
                                grid[i][j] = column[i];
                            }
                        }
                        break;
                        
                    case 'down':
                        for (let j = 0; j < gridSize; j++) {
                            let column = [];
                            for (let i = gridSize - 1; i >= 0; i--) {
                                if (grid[i][j] !== 0) {
                                    column.push(grid[i][j]);
                                }
                            }
                            
                            // 合并相同数字
                            for (let i = 0; i < column.length - 1; i++) {
                                if (column[i] === column[i + 1]) {
                                    column[i] *= 2;
                                    column[i + 1] = 0;
                                    score += column[i];
                                    scoreDisplay.textContent = score;
                                }
                            }
                            
                            // 移除0并填充
                            column = column.filter(val => val !== 0);
                            while (column.length < gridSize) {
                                column.push(0);
                            }
                            
                            // 更新列
                            for (let i = gridSize - 1, k = 0; i >= 0; i--, k++) {
                                if (grid[i][j] !== column[k]) {
                                    moved = true;
                                }
                                grid[i][j] = column[k];
                            }
                        }
                        break;
                        
                    case 'left':
                        for (let i = 0; i < gridSize; i++) {
                            let row = [];
                            for (let j = 0; j < gridSize; j++) {
                                if (grid[i][j] !== 0) {
                                    row.push(grid[i][j]);
                                }
                            }
                            
                            // 合并相同数字
                            for (let j = 0; j < row.length - 1; j++) {
                                if (row[j] === row[j + 1]) {
                                    row[j] *= 2;
                                    row[j + 1] = 0;
                                    score += row[j];
                                    scoreDisplay.textContent = score;
                                }
                            }
                            
                            // 移除0并填充
                            row = row.filter(val => val !== 0);
                            while (row.length < gridSize) {
                                row.push(0);
                            }
                            
                            // 更新行
                            for (let j = 0; j < gridSize; j++) {
                                if (grid[i][j] !== row[j]) {
                                    moved = true;
                                }
                                grid[i][j] = row[j];
                            }
                        }
                        break;
                        
                    case 'right':
                        for (let i = 0; i < gridSize; i++) {
                            let row = [];
                            for (let j = gridSize - 1; j >= 0; j--) {
                                if (grid[i][j] !== 0) {
                                    row.push(grid[i][j]);
                                }
                            }
                            
                            // 合并相同数字
                            for (let j = 0; j < row.length - 1; j++) {
                                if (row[j] === row[j + 1]) {
                                    row[j] *= 2;
                                    row[j + 1] = 0;
                                    score += row[j];
                                    scoreDisplay.textContent = score;
                                }
                            }
                            
                            // 移除0并填充
                            row = row.filter(val => val !== 0);
                            while (row.length < gridSize) {
                                row.push(0);
                            }
                            
                            // 更新行
                            for (let j = gridSize - 1, k = 0; j >= 0; j--, k++) {
                                if (grid[i][j] !== row[k]) {
                                    moved = true;
                                }
                                grid[i][j] = row[k];
                            }
                        }
                        break;
                }
                
                // 如果有移动，添加新方块并检查游戏状态
                if (moved) {
                    addRandomTile();
                    updateGridDisplay();
                    
                    if (isGameOver()) {
                        gameOverDisplay.style.display = 'flex';
                    }
                }
            }
            
            // 检查游戏是否结束
            function isGameOver() {
                // 检查是否有空格
                for (let i = 0; i < gridSize; i++) {
                    for (let j = 0; j < gridSize; j++) {
                        if (grid[i][j] === 0) {
                            return false;
                        }
                    }
                }
                
                // 检查是否有可合并的相邻方块
                for (let i = 0; i < gridSize; i++) {
                    for (let j = 0; j < gridSize; j++) {
                        const current = grid[i][j];
                        
                        // 检查右侧
                        if (j < gridSize - 1 && grid[i][j + 1] === current) {
                            return false;
                        }
                        
                        // 检查下方
                        if (i < gridSize - 1 && grid[i + 1][j] === current) {
                            return false;
                        }
                    }
                }
                
                return true;
            }
            
            // 键盘控制
            document.addEventListener('keydown', (e) => {
                if (gameOverDisplay.style.display === 'flex') return;
                
                switch (e.key) {
                    case 'ArrowUp':
                    case 'w':
                    case 'W':
                        moveTiles('up');
                        break;
                    case 'ArrowDown':
                    case 's':
                    case 'S':
                        moveTiles('down');
                        break;
                    case 'ArrowLeft':
                    case 'a':
                    case 'A':
                        moveTiles('left');
                        break;
                    case 'ArrowRight':
                    case 'd':
                    case 'D':
                        moveTiles('right');
                        break;
                }
            });
            
            // 重新开始游戏
            restartButton.addEventListener('click', initGame);
            tryAgainButton.addEventListener('click', initGame);
            
            // 初始化游戏
            initGame();
        });
    </script>
</body>
</html>